package us.mooresr.webtroopmanager.client.activity;

import us.mooresr.webtroopmanager.client.ClientFactory;
import us.mooresr.webtroopmanager.client.SecurityManager;
import us.mooresr.webtroopmanager.client.TroopManagerService;
import us.mooresr.webtroopmanager.client.TroopManagerServiceAsync;
import us.mooresr.webtroopmanager.client.events.PermissionChangedEvent;
import us.mooresr.webtroopmanager.client.events.PermissionChangedHandler;
import us.mooresr.webtroopmanager.client.place.DashboardPlace;
import us.mooresr.webtroopmanager.client.place.LoginPlace;
import us.mooresr.webtroopmanager.client.ui.DashboardView;
import us.mooresr.webtroopmanager.shared.Privilege;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class DashboardActivity extends MyActivity implements DashboardView.Presenter {
	
	public DashboardActivity(DashboardPlace place, ClientFactory clientFactory) {
		super(place, clientFactory);
	}
	

	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		
		DashboardView dashboardView = clientFactory.getDashboardView();
		dashboardView.setPresenter(this);
		dashboardView.setStatus("Logged in");
		panel.setWidget(dashboardView.asWidget());
		
		eventBus.addHandler(PermissionChangedEvent.TYPE, new PermissionChangedHandler() {

			@Override
			public void onPermissionChanged(PermissionChangedEvent event) {
				DashboardView dashboardView = clientFactory.getDashboardView();
				dashboardView.permissionsChanged();
				
			}
			
		});

		
	}

	
	@Override
	public void doLogout() {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);

		AsyncCallback<Void> callback = new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Logout failed due to internal error");

			}

			@Override
			public void onSuccess(Void result) {
				SecurityManager securityManager = clientFactory.getSecurityManager();
				securityManager.setUserId(null);
				goTo(new LoginPlace());

			}

		};
		
		troopManagerService.doLogout(callback);
	}
	

}
